'''
Created on 18 Jul 2013

@author: Matt
'''
from Crypto.Cipher import AES
import binascii
from MattCrypto.CryptoFunctions import strToBits, pad, bitsToHex, bytesToBits,\
    xor, hexStrToBits, unpad

if __name__ == '__main__':
    hexKey = "140b41b22a29beb4061bda66b6747e14"#
    
    myAES = AES.new(bytes.fromhex(hexKey))
    myAES.mode = AES.MODE_CBC
    plainBits = strToBits("Pay Bob 100$")
    hexPlain = pad(bitsToHex(plainBits))
    encryptedHex = bitsToHex(bytesToBits(myAES.encrypt(hexPlain)))
    print(encryptedHex)
    
    plainBits2 = strToBits("Pay Bob 500$")
    hexPlain2 = pad(bitsToHex(plainBits2))
    encryptedHex2 = bitsToHex(bytesToBits(myAES.encrypt(hexPlain2)))
    print(encryptedHex2)
    
    xorBits1 = [0 for x in range(0, (16*4))] + strToBits("1") + [0 for x in range(0, (30*4))]
    xorBits5 = [0 for x in range(0, (16*4))] + strToBits("5") + [0 for x in range(0, (30*4))]
    
    ivX = encryptedHex[0:32]
    ivX = bitsToHex(xor(hexStrToBits(ivX), xorBits1))
    ivX = bitsToHex(xor(hexStrToBits(ivX), xorBits5))
    
    print("======DECRYPT=====")
    print(encryptedHex)
    print(binascii.unhexlify(unpad(str(myAES.decrypt(bytes.fromhex(encryptedHex)))[2:-1])))
    print(encryptedHex2)
    print(binascii.unhexlify(unpad(str(myAES.decrypt(bytes.fromhex(encryptedHex2)))[2:-1])))